package com.sangeng.controller;

import com.sangeng.constant.enums.AppHttpCodeEnum;
import com.sangeng.domain.core.ResponseResult;
import com.sangeng.domain.dto.LinkInsertDto;
import com.sangeng.domain.dto.LinkPageDto;
import com.sangeng.domain.entity.Link;
import com.sangeng.domain.vo.LinkUpdateVo;
import com.sangeng.service.LinkService;
import com.sangeng.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/content/link")
public class LinkController {

    @Autowired
    private LinkService linkService;

    @PreAuthorize("@ps.hasPermission('content/link/index')")
    @RequestMapping("/list")
    public ResponseResult list(LinkPageDto linkPageDto) {
        return linkService.getAllLinkPages(linkPageDto);
    }

    @PostMapping
    public ResponseResult addLink(@RequestBody LinkInsertDto linkInsertDto) {
        return linkService.save(BeanUtil.copyBean(linkInsertDto, Link.class)) ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.INSERT_ERROR);
    }

    @GetMapping("/{id}")
    public ResponseResult getLinkById(@PathVariable Long id) {
        return ResponseResult.okResult(BeanUtil.copyBean(linkService.getById(id), LinkUpdateVo.class));
    }

    @PutMapping
    public ResponseResult updateLink(@RequestBody LinkUpdateVo linkUpdateVo) {
        return linkService.updateById(BeanUtil.copyBean(linkUpdateVo, Link.class)) ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteLink(@PathVariable Long id) {
        return linkService.removeById(id) ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.DELETE_ERROR);
    }

    @PutMapping("/changeLinkStatus")
    public ResponseResult changeStatus(@RequestBody LinkUpdateVo linkUpdateVo) {
        return linkService.updateById(BeanUtil.copyBean(linkUpdateVo, Link.class)) ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }
}
